<?php
/**
 *
 * Author: pyc
 * Date: 2017/8/4 9:09
 * Time: 09:44
 * intro:紫元物业
 */

class UtilitiesService extends BaseService
{
    private $accountId;
    private $server;                        //基础信息

    public function __construct()
    {
        parent::__construct();
        if(!$this->accountId){
            $this->accountId = (C('site_url') == 'http://wap.xt.beescrm.com') ? 65 : 60;
        }
        $this->server = Service("BuildBaseInfo");
        $this->server->setProperties(array('accountId'=>$this->accountId));
    }


    /**
     * 获得当前用户的信息
     * @param int $userId
     * @return array|mixed
     * @Auth    : piyechao
     * @Now     :2017/8/8 12:27
     */
    public function getUserInfoByUserId($userId = 0)
    {
        $cacheKey = 'user_info'.$userId;
        $userInfo = RedisService::get($cacheKey);
//        $userInfo = null;
        if(empty($userInfo)){
            $condition = array('user_id'=>$userId);
            $userRow = M('User')->where($condition)->field('real_name,mobile,id_card,type')->find();
            $utilitiesUserRow = M('UtilitiesUser')->where($condition)->field('user_utilities_id,room_code,user_type')->find();
            if(!$utilitiesUserRow){
                if(!$userRow['id_card'] ){
                    $userRow['id_card'] = '';
                }
                $data = array('user_id'=>$userId ,'account_id'=>$this->accountId ,'user_utilities_id'=>$userRow['id_card']);
                $id = M('UtilitiesUser')->add($data);
                $utilitiesUserRow = M('UtilitiesUser')->where(array('utilities_id',$id))->find();
            }
            $userInfo = array_merge($userRow,$utilitiesUserRow);
            if($userInfo['room_code']){
                $address = $this->getAddressByRoomUtilitiesId($userInfo['room_code']);
                if($userInfo['type'] != 2){//学生
                    $userInfo['address'] = $address['community_name'].' '.$address['building_name'].' '.$address['room'];
                }else{//商户
                    $userInfo['address'] = $address['room'];
                }
            }
            $userInfo = serialize($userInfo);
            RedisService::set($cacheKey ,$userInfo ,120);
        }
        $userInfo = unserialize($userInfo);
        return $userInfo;
    }

    /**
     * 更新户主
     * @param int $userId
     * @Auth    : piyechao
     * @Now     :2017/8/4 12:37
     */
    public function updateUserInfo($userId = 0)
    {
        $cacheKey = 'user_info'.$userId;
        $re = RedisService::get($cacheKey);
        if($re){
            RedisService::rm($cacheKey);
        }
    }

    /**
     * 发送充值消息
     * @param array $order
     * @Auth    : piyechao
     * @Now     :2017/8/10 20:11
     */
    public function sendRechargeMessage($order)
    {
//        wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$order：'.var_export($order ,true) , 'Utilities');
        $recharge_type = $this ->getTypeNameByTypeId($order['recharge_type']) ;
        $address = $address = $this->getAddressByRoomUtilitiesId($order['room_code']);
        vendor('Wechat.WechatApi');
        $wechat = M('Wechat')->where(array('account_id' => $this->accountId))->find();//getField('wechat_id');
        $weixin = new WechatApi($wechat['wechat_id']);
        if($this->accountId == 60){
            $template_id = 'b927Utg2VSH5U2K1ivojHAGacjyUUt_s-i9GzjRTTzY';
        }elseif($this->accountId == 65){
            $template_id = 'kzEHDlZ6sTdj0OUP6Z2biQ_n7D0bB_3I5gVy9LdDLTc';
        }
        $jump_url = C('site_url') . U('base/utilities/rechargeMessage', array('utilities_set_id' =>1,'order_id'=>$order['order_id']));

        $condition = array('account_id'=>$this->accountId ,'cut_off'=>0);
        $push = M('UtilitiesPush')->where($condition)->select();
        foreach ($push as $v) {
            $buildingIds = explode(",",$v['auth_id']);
            if(!in_array($address['building_id'] ,$buildingIds)){
                continue;
            }
            $userId = $v['user_id'];//管理员id
            $openId = M('WechatUser')->where(array('user_id' =>$userId))->getField('openid');
            $info = array(
                'first' => array("value" => '您有一条新的订单，请及时办理充值！'),
                'keyword1' => array("value" => $recharge_type.'充值'),
                'keyword2' => array("value" => $address['community_name'].' '.$address['building_name'].' '.$address['room']),
                'keyword3' => array("value" => date('Y-m-d H:i')),
                'remark' => array("value" => "详情"),
            );
            $weixin->messageTpl($wechat['appid'], $wechat['appsecret'], $openId, $template_id, $info, $jump_url);
        }
    }

    /**
     *  缴费通知
     * @Auth    : piyechao
     * @Now     :2017/9/4 17:19
     */
    public function sendPanymentMessage($list = array())
    {
        //获得欠费信息列表
//        $where = array('account_id'=>$this->accountId ,'cut_off'=>0);
//        $balanceList = M('UtilitiesBalance')->where($where)->select();
//        $list = array();
//        $key = 0;
//        foreach ($balanceList as $k => $v) {
//            if($v['balance_cold_water'] < 0){
//                $list[$key]['type'] = 1;
//                $list[$key]['money'] = abs($v['balance_cold_water']);
//                $list[$key]['room_code'] =$v['room_code'];
//                $key++;
//            }
//            if($v['balance_hot_water'] < 0){
//                $list[$key]['type'] = 2;
//                $list[$key]['money'] = abs($v['balance_hot_water']);
//                $list[$key]['room_code'] =$v['room_code'];
//                $key++;
//            }
//            if($v['balance_electric'] < 0){
//                $list[$key]['type'] = 3;
//                $list[$key]['money'] = abs($v['balance_electric']);
//                $list[$key]['room_code'] =$v['room_code'];
//                $key++;
//            }
//        }

        vendor('Wechat.WechatApi');
        $wechat = M('Wechat')->where(array('account_id' => $this->accountId))->find();//getField('wechat_id');
        $weixin = new WechatApi($wechat['wechat_id']);
        $jump_url =  C('site_url')."/index.php?g=Base&m=Utilities&a=paymentDetail&utilities_set_id=1";
        if($this->accountId == 60){
            $template_id = 'b927Utg2VSH5U2K1ivojHAGacjyUUt_s-i9GzjRTTzY';
        }elseif($this->accountId == 65){
            $template_id = 'LSvZVRvksDAOcKonsQp_KK4JfF_llIaqugx3ZV-lFis';//'5bfM5cVEmNGE59PwjpfWS3BYhZaiJSyYlD3lKYzC-Bc';
        }
        foreach ($list as $k => $v) {
            $money = -$v['money'];
            if($money < 0){
                $moneyType = '欠费';
            }else{
                $moneyType = '不足';
            }
            $money = abs($money);
            $type_name = $this->getTypeNameByTypeId($v['type']);
            $userId = M('UtilitiesUser')->where(array('room_code'=>$v['room_code'] ,'user_type'=>3,'account_id'=>$this->accountId))->getField('user_id');
            if(!$userId){
                continue;
            }
            $openId = M('WechatUser')->where(array('user_id' =>$userId))->getField('openid');
            $address = $this->getAddressByRoomUtilitiesId($v['room_code']);
            $info = array(
                'first' => array("value" => "您好，您的寝室{$type_name}已{$moneyType}{$money}元,请及时充值"),
                'keyword1' => array("value" => $type_name.'缴费'),
                'keyword2' => array("value" => $address['community_name'].' '.$address['building_name'].' '.$address['room']),
                'keyword3' => array("value" => date('Y-m-d H:i')),
                'remark' => array("value" => "详情"),
            );
            $weixin->messageTpl($wechat['appid'], $wechat['appsecret'], $openId, $template_id, $info, $jump_url);
        }
    }

    /**
     * 充值同步接口
     * @param $room_code
     * @param $money
     * @param $type
     * @param $room_type
     * @Auth    : piyechao
     * @Now     :2017/8/25 13:49
     */
    public function rechargeInterface($room_code ,$money ,$type )
    {
//$money = 140;//测试
        $room = M('UtilitiesRoom')->where(array('room_code'=>$room_code ,'account_id'=>$this->accountId ,'cut_off'=>0))->find();
        try{
            $client = $this->_des3CSharpsObject();
            if(!is_object($client)){
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client.'-$room_code：'. $room_code , 'Utilities');                exit;
            }
            if($type == 1){//冷水
                $room['cold_water_door_id'] = substr(strval($room['cold_water_door_id']+10000000),1,7);
                $params = array('door_id'=>$room['cold_water_door_id'] ,'money'=>(float)$money ,'type'=>0);
            }elseif($type == 2){//热水
                $room['hot_water_door_id'] =  substr(strval($room['hot_water_door_id']+1000000000),1,9);
                $params = array('door_id'=>$room['hot_water_door_id'] ,'money'=>(float)$money ,'type'=>1);
            }elseif($type == 3){//电
                $room['ele_door_id'] =  substr(strval($room['ele_door_id']+10000000),1,7);
                $params = array('door_id'=>$room['ele_door_id'] ,'money'=>(float)$money ,'type'=>2);
            }
            $strJson = $client->__soapCall('SubscribeAdd', array('parameters' => $params));
            $callResArr = json_decode($strJson->SubscribeAddResult, true);
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$callResArr：'.var_export($callResArr ,true) , 'Utilities');
            return $callResArr['Result'];
        }catch (Exception $e) {
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-rechargeInterface：'. $e->getMessage() , 'Utilities');
            exit;
        }

    }

    /**
     * 缴费同步接口
     * @param $order
     * @return mixed
     * @Auth    : piyechao
     * @Now     :2017/9/6 12:34
     */
    public function paymentInterface($order)
    {
        try{
            $client = $this->_des3CSharpsObject();
            if(!is_object($client)){
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client.'行-$order：'. var_export($order,true) , 'Utilities');                exit;
            }
            $room = M('UtilitiesRoom')->where(array('room_code'=>$order['room_code'] ,'account_id'=>$this->accountId ,'cut_off'=>0))->find();

            if($order['payment_cold_water'] > 0){
                $room['cold_water_door_id'] =  substr(strval($room['cold_water_door_id']+10000000),1,7);
                $params = array('door_id'=>$room['cold_water_door_id'],'type'=>0 ,'money'=>(float)$order['payment_cold_water'] ,'room_type'=>(int)$room['room_type']);
                $strJson = $client->__soapCall('updateSubscribe', array('parameters' => $params));
                $callResArr[] = json_decode($strJson->updateSubscribeResult, true);
            }
            if($order['payment_hot_water'] > 0){
                $room['hot_water_door_id'] =  substr(strval($room['hot_water_door_id']+1000000000),1,9);
                $params = array('door_id'=>$room['hot_water_door_id'],'type'=>1 ,'money'=>(float)$order['payment_hot_water'] ,'room_type'=>(int)$room['room_type']);
                $strJson = $client->__soapCall('updateSubscribe', array('parameters' => $params));
                $callResArr[] = json_decode($strJson->updateSubscribeResult, true);
            }
            if($order['payment_electric'] > 0){
                $room['ele_door_id'] =  substr(strval($room['ele_door_id']+10000000),1,7);
                $params = array('door_id'=>$room['ele_door_id'],'type'=>2 ,'money'=>(float)$order['payment_electric'] ,'room_type'=>(int)$room['room_type']);
                $strJson = $client->__soapCall('updateSubscribe', array('parameters' => $params));
                $callResArr[] = json_decode($strJson->updateSubscribeResult, true);
            }
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$callResArr：'.var_export($callResArr ,true) , 'Utilities');
            return $callResArr['Result'];
        }catch (Exception $e) {
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-paymentInterface：'. $e->getMessage() , 'Utilities');
            exit;
        }
    }

    /**
     *  开户同步接口
     * @param $order
     * @return string
     * @Auth    : piyechao
     * @Now     :2017/8/31 10:36
     */
    public function openAccountInterface ($order)
    {
        try{
            $client = $this->_des3CSharpsObject();
            if(!is_object($client)){
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client.'行-$order：'. var_export($order,true) , 'Utilities');
                exit;
            }

            //保存账户
            $data = array(
                'account_id'=>$this->accountId,
                'room_code'=>$order['room_code'],
                'user_id'=>$order['user_id'],
                'update_time'=>time(),
            );

            //热水开户
            $room_code =  substr(strval($order['room_code']+100000),1,5);
            //获得开户人信息
            $userInfo = M('User')->find($order['user_id']);
            if($userInfo){
                $desc = $userInfo['real_name'].$userInfo['id_card'];
            }else{
                $desc = '';
            }
            $params = array('bail'=>(float)$order['open_account_fee'],'chamber_id'=>$room_code ,'subcribe'=>(float)$order['pledge_fee'] ,'hotWaterMeterStop'=>0 ,'desc'=>$desc);
            $strJson1 = $client->__soapCall('HotWaterDoorAppend', array('parameters' => $params));
            $callResArr1 = json_decode($strJson1->HotWaterDoorAppendResult, true);
            if($callResArr1['Flag'] && $callResArr1['Flag'] === 'OK'){
                $hot_water_info = json_decode($callResArr1['Result'] , true);
                if($hot_water_info['Alias']){
                    $data['hot_water_door_id'] = $hot_water_info['Alias'];
                }
            }

            //冷水开户
            $params = array('chamberID'=>$room_code ,'countPerson'=>1 ,'loginDate'=>time() ,'desc'=>'' ,'doorMeterState'=>0,'doorType'=>0);
            $strJson2 = $client->__soapCall('ColdWaterDoorAppend', array('parameters' => $params));
            $callResArr2 = json_decode($strJson2->ColdWaterDoorAppendResult, true);
            if($callResArr2['Flag'] && $callResArr2['Flag'] === 'OK'){
                $cold_water_info = json_decode($callResArr2['Result'] , true);
                if($cold_water_info['Alias']){
                    $data['cold_water_door_id'] = $cold_water_info['Alias'];
                }
            }

            //电开户
            $params = array('chamberID'=>$room_code ,'countPerson'=>1 ,'loginDate'=>time() ,'desc'=>'' ,'doorMeterState'=>0,'doorType'=>0,'airConditionState'=>0,'list'=>'','telephone'=>'');
            $strJson3 = $client->__soapCall('EleDoorAppend', array('parameters' => $params));
            $callResArr3 = json_decode($strJson3->EleDoorAppendResult ,true);
            if($callResArr3['Flag'] && $callResArr3['Flag'] === 'OK'){
                $ele_info = json_decode($callResArr3['Result'] , true);
                if($ele_info['Alias']){
                    $data['ele_door_id'] = $ele_info['Alias'];
                }
            }
            //同步水电费账户
            $this->_saveUtilitiesRoom($order['room_code'] ,$data);

wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$callResArr1：'.var_export($callResArr1 ,true).'--'.var_export($callResArr2 ,true).'--'.var_export($callResArr3 ,true) , 'Utilities');
            //预充值
            $this->rechargeInterface($order['room_code'] ,$order['pledge_fee']  ,$order['recharge_type'] );
        }catch (Exception $e) {
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-openAccountInterface：'. $e->getMessage() , 'Utilities');
            exit;
        }

    }

    /**
     * 账号余额同步接口
     * @param $room_code
     * @Auth    : piyechao
     * @Now     :2017/8/25 13:41
     */
    public function accountBalanceInterface($room_code)
    {
        try {
            $client = $this->_des3CSharpsObject();
            if(!is_object($client)){
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client.'行-$room_code：'. $room_code , 'Utilities');                exit;
            }
            $roomCode =  substr(strval($room_code+100000),1,5);
            $params = array('chamber'=>$roomCode);
            $strJson = $client->__soapCall('searchAccount', array('parameters' => $params));
            $callResArr = json_decode($strJson->searchAccountResult, true);
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$callResArr：'.var_export($callResArr ,true) , 'Utilities');
            $data['balance_cold_water'] = $data['balance_hot_water'] = $data['balance_electric'] = 0;
            $parms = array();
            foreach ($callResArr as $v) {
                //同步余额信息
                switch($v['Flag']){
                    case '冷水剩余费用':
                        $data['balance_cold_water'] = abs($v['Result']);
                        break;
                    case '冷水应缴费用':
                        $data['balance_cold_water'] = -abs($v['Result']);
                        break;
                    case '热水剩余费用':
                        $data['balance_hot_water'] = abs($v['Result']);
                        break;
                    case '热水应缴费用':
                        $data['balance_hot_water'] = -abs($v['Result']);
                        break;
                    case '应缴费用':
                        $data['balance_electric'] = -abs($v['Result']);
                        break;
                    case '剩余费用':
                        $data['balance_electric'] = abs($v['Result']);
                        break;
                    case 'ColdWaterDoor':
                        $cold = json_decode($v['Result'] , true);
                        $parms['cold_water_door_id'] = $cold['Alias'] ? $cold['Alias'] : 0;
                        break;
                    case 'HotWaterDoor':
                        $hot = json_decode($v['Result'] , true);
                        $parms['hot_water_door_id'] = $hot['Alias'] ? $hot['Alias'] : 0;
                        break;
                    case 'ElecMeterDoor':
                        $ele = json_decode($v['Result'] , true);
                        $parms['ele_door_id'] = $ele['Alias'] ? $ele['Alias'] : 0;
                        break;
                }
            }
            //同步水电费账户
            if($parms){
                $parms['account_id'] = $this->accountId;
                $parms['room_code'] = $room_code;
                $this->_saveUtilitiesRoom($room_code ,$parms);
            }

            //是否销户
            if($parms['hot_water_door_id']){
                $data['isOpenAccount'] = true;
            }else{
                $data['isOpenAccount'] = false;
            }

            //返回余额信息
            return $data;
        } catch (Exception $e) {
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-accountBalanceInterface：'. $e->getMessage() , 'Utilities');
            exit;
        }
    }

    /**
     * 欠费消息同步数据库
     * @return mixed
     * @Auth    : piyechao
     * @Now     :2017/8/29 16:06
     */
    public function arrmessageInterface()
    {
        try {
            $client = $this->_des3CSharpsObject();
            if(!is_object($client)){
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client , 'Utilities');                exit;
            }
            $params = array();
            $strJson = $client->__soapCall('arrmessage',array('parameters' => $params));
            $callResArr = json_decode($strJson->arrmessageResult, true);
            $result = json_decode($callResArr['Result'], true);
            //Alias_id,Arr_type,Room_type,Arr_money
            //通过Alias_id,Arr_type找到对应的账户
            if(!is_array($result)){
                return false;
            }
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$callResArr：'. var_export($callResArr,true) , 'Utilities');
            foreach ($result as $k=>$v) {
                $condition = array('account_id'=> $this->accountId,'cut_off'=>0);
                $data = array();
                $roomCode = '';
                if($v['Arr_type'] == 1){
                    $condition['cold_water_door_id'] =  trim($v['Alias_id']);
                    $data['balance_cold_water'] = -$v['Arr_money'];
                }elseif($v['Arr_type'] == 0){
                    $condition['hot_water_door_id'] = trim($v['Alias_id']);
                    $data['balance_hot_water'] = -$v['Arr_money'];
                }elseif($v['Arr_type'] == 2){
                    $condition['ele_door_id'] = trim($v['Alias_id']);
                    $data['balance_electric'] = -$v['Arr_money'];
                }
                $roomCode = M('UtilitiesRoom')->where($condition)->getField('room_code');
                if($roomCode){
                    $re = M('UtilitiesBalance')->where(array('room_code'=>$roomCode,'account_id'=>$this->accountId))->find();
                    if($re){
                        $data['balance_id'] = $re['balance_id'];
                        $data['update_time'] = time();
                    }else{
                        $data['account_id'] = $this->accountId;
                        $data['room_code'] = $roomCode;
                        $data['create_time'] = time();
                    }
                    M('UtilitiesBalance')->update($data);
//                    wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-UtilitiesBalance：'. M('UtilitiesBalance')->_sql() , 'Utilities');
                }
            }
        } catch (Exception $e) {
wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-arrmessageInterface：'. $e->getMessage() , 'Utilities');
            exit;
        }
    }


    /**
     * 定时推送消息
     * @return bool
     * @Auth    : piyechao
     * @Now     :2017/9/22 9:28
     */
    public function pushPanymentInterface()
    {
        try {
            $client = $this->_des3CSharpsObject();
            if(!is_object($client)){
                wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client , 'Utilities');                exit;
            }
            $params = array();
            $strJson = $client->__soapCall('arrmessage',array('parameters' => $params));
            $callResArr = json_decode($strJson->arrmessageResult, true);
            $result = json_decode($callResArr['Result'], true);
            //Alias_id,Arr_type,Room_type,Arr_money
            //通过Alias_id,Arr_type找到对应的账户
            if(!is_array($result)){
                return false;
            }
            wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$callResArr：'. var_export($callResArr,true) , 'Utilities');
            $list = array();
            foreach ($result as $k=>$v) {
                $condition = array('account_id'=> $this->accountId,'cut_off'=>0);
                if($v['Arr_type'] == 1){
                    $condition['cold_water_door_id'] =  trim($v['Alias_id']);
                    $list[$k]['type'] = 1;
                }elseif($v['Arr_type'] == 0){
                    $condition['hot_water_door_id'] = trim($v['Alias_id']);
                    $list[$k]['type'] = 2;
                }elseif($v['Arr_type'] == 2){
                    $condition['ele_door_id'] = trim($v['Alias_id']);
                    $list[$k]['type'] = 3;
                }
                $roomCode = M('UtilitiesRoom')->where($condition)->getField('room_code');
                if(!$roomCode){
                    unset($list[$k]);
                    continue;
                }
                $list[$k]['room_code'] = $roomCode;
                $list[$k]['money'] = $v['Arr_money'];
            }
            //欠费消息推送
            //wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-list：'.var_export($list ,true) , 'Utilities');
            $this->sendPanymentMessage($list);
        } catch (Exception $e) {
            wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-arrmessageInterface：'. $e->getMessage() , 'Utilities');
            exit;
        }
    }

    /**
     * 判断开户接口
     * @Auth    : piyechao
     * @Now     :2017/9/21 10:44
     */
    public function isOpenAccountInterface($room_code)
    {
        $client = $this->_des3CSharpsObject();
        if(!is_object($client)){
            wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-$client：'. $client.'行-$room_code：'. $room_code , 'Utilities');                exit;
        }
        $roomCode =  substr(strval($room_code+100000),1,5);
        $params = array('chamber'=>$roomCode);
        $strJson = $client->__soapCall('searchAccount', array('parameters' => $params));
        $callResArr = json_decode($strJson->searchAccountResult, true);

        foreach ($callResArr as $v) {
            if($v['Flag'] == 'ColdWaterDoor'){
                $cold = json_decode($v['Result'] , true);
                if($cold){
                    //已开户
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获得接口对象
     * @return SoapClient
     * @Auth    : piyechao
     * @Now     :2017/8/30 9:21
     */
    private function _des3CSharpsObject()
    {
        $key = 'eml5dWFuMTM0c2RmZzEjQCRAZmFnYXNn';//C('zywyapi.des_key');
        $iv = 'enlpdjEyM2E=';//C('zywyapi.des_iv');
        $user = 'WebService';//C('zywyapi.des_user');
        $password = 'test';//C('zywyapi.des_password');
        $client_url = 'http://223.93.172.88:8088/WebService.asmx?wsdl';//C('zywyapi.des_client');
        $namespace = 'http://tempuri.org/';//C('zywyapi.des_namespace');
        $class_name = 'ServiceCredential';//C('zywyapi.class_name');
        Vendor('OneCard.Des3CSharp');
        try {
            $Des3CSharps = new Des3CSharp($key ,$iv);
            $password = $Des3CSharps->encrypt($password);
            $auth = array('User'=> $user,'Password'=>$password);

            //允许引用外部xml实体
            libxml_disable_entity_loader(false);
            $header = new SoapHeader($namespace, $class_name, $auth, true);
            $client = new SoapClient($client_url);
            $client->__setSoapHeaders($header);
            return $client;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * 查询寝室是否需缴费
     * @Auth    : piyechao
     * @Now     :2017/8/29 15:25
     */
    public function updateSubscribe()
    {
        $room_code = '01101';
        $room = M('UtilitiesRoom')->where(array('room_code'=>$room_code ,'account_id'=>$this->accountId ,'cut_off'=>0))->find();
        //webserviec头部安全验证
        $client = $this->_des3CSharpsObject();
        //热水 寝室号，冷水 账号ID
        $params = array('door_id'=>'0701104','doorType'=>0 ,'subscribeType'=>0);
        $strJson = $client->__soapCall('synSubscribe', array('parameters' => $params));
        $callResArr = $strJson->synSubscribeResult;
        return $callResArr;
    }

    /**
     * 更新UtilitiesRoom表
     * @param string $roomCode
     * @param array $data
     * @Auth    : piyechao
     * @Now     :2017/9/6 12:24
     */
    private function _saveUtilitiesRoom($roomCode = '' ,$data = array())
    {
        $condition = array('account_id'=>$this->accountId,'room_code'=>$roomCode,'cut_off'=>0);
        $utilities_room = M('UtilitiesRoom')->where($condition)->find();
        if($utilities_room){
            $data['utilities_id'] = $utilities_room['utilities_id'];
        }
        M('UtilitiesRoom')->update($data);
        wLog(date('Y-m-d H:i:s').'-'.__LINE__.'行-UtilitiesRoom_sql：'.  M('UtilitiesRoom')->_sql() , 'Utilities');
    }

    /**
     * 获得充电类型名称
     * @param int $type_id
     * @return bool|string
     * @Auth    : piyechao
     * @Now     :2017/7/31 16:12
     */
    public function getTypeNameByTypeId($type_id = 0)
    {
        switch($type_id){
            case 1:
                return '冷水';
                break;
            case 2:
                return '热水';
                break;
            case 3:
                return '电费';
                break;
            default:
                return false;
        }
    }

    /**
     * 通过房间唯一标识 获得地址信息
     * @param int $roomCode
     * @return array
     * @Auth    : piyechao
     * @Now     :2017/8/9 13:18
     */
    public function getAddressByRoomUtilitiesId($roomCode = 0)
    {
        $data = array();
        if(!$roomCode){
            return false;
        }
        $condition = array('room_code' => $roomCode ,'account_id'=>$this->accountId);
        $room = M('Room')->where($condition)->find();
        if(!$room){
            return false;
        }
        if($room['room_type'] == 0){//学生
            $floor = $this->server->getFloorInfo($room['floor_id']);
            if(!$floor){
                return false;
            }

            $build = $this->server->getBuildInfo($floor['building_id']);
            if(!$build){
                return false;
            }
            $community = $this->server->getCommunityInfo($build['community_id']);
            if(!$condition){
                return false;
            }
            if(!strpos($build['building_name'] ,'幢')){
                $build['building_name'] = $build['building_name'].'幢';
            }
            $room['room_name'] = substr($room['room_name'],-3);

            $data = array(
                'community_id' => $community['community_id'],
                'building_id' => $build['building_id'],
                'room_id' => $room['room_id'],
                'community_name' => $community['community_name'],
                'building_name' => $build['building_name'],
                'room' => $room['room_name'],
            );
        }else{//商户
            $data = array(
                'room' =>$room['room_name']
            );
        }
        return $data;
    }
}